package cn.edu.ecust.common.interceptor;

import cn.edu.ecust.common.constant.HttpRespCode;
import cn.edu.ecust.common.util.Resp;
import cn.edu.ecust.common.util.UserHolder;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import org.springframework.http.MediaType;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author cjj
 * @date 2023/09/03 17:38
 **/
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(UserHolder.getUser() == null){
            responseException(new Resp(HttpRespCode.UNAUTHORIZED),response);
            return false;
        }
        return true;
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        UserHolder.removeUser();
    }

    /**
     * 返回异常
     *
     * @param resp
     */
    private void responseException(Resp resp, HttpServletResponse response) throws Exception {
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.getWriter().print(JSONUtil.toJsonStr(resp));
    }

}
